/**
 * Created by zhulingxiao on 2017/6/7.
 */
import { myFetch } from '../../utils/func'
import {tableLoading,tableFinish} from './table'

export const MENU_UPDATE = 'MENU_UPDATE';

export const menuFetch = (cb = function () {} ) => {

  return dispatch => {
    dispatch(tableLoading());
    return myFetch('/api/v1/menu/list.php')

      .then(data=>{

        let sideMenu = data.data;

        for(let i in sideMenu){

          sideMenu[i].key = i;

          let children = sideMenu[i].children;

          for(let j in children){

            children[j].key ='' + children[j].title + children[j].idx;

            delete children[j].children;

          }

        }
        dispatch({ type : MENU_UPDATE, data : sideMenu});
        dispatch(tableFinish());
        cb(sideMenu)

      })

  }

};

export const menuDelete = (sysid) => {
  return dispatch => {

    return myFetch('/api/v1/menu/del.php',{
      SysID:sysid
    })

      .then(()=>{

        dispatch(menuFetch())

      })

  }

};

export const menuUpdate = (data) => {

  return dispatch => {

    return myFetch('/api/v1/menu/update.php',{
      sysID:data.SysID,
      title:data.title,
      icon:data.icon,
      link:data.link,
      qx:data.qx,
      idx:data.idx
    })

      .then(()=>{

        dispatch(menuFetch())

      })

  }

};

export const menuAdd = (data) => {

  return dispatch => {

    return myFetch('/api/v1/menu/add.php', {
      title: data.title,
      icon: data.icon,
      link: data.link,
      qx: data.qx,
      idx: data.idx,
      parentid: data.parentid
    })

      .then(() => {

        dispatch(menuFetch())

      })
  }
};

